package com.zg.autoform.service.impl;


import com.zg.autoform.dto.ImportFieldConfig;
import com.zg.autoform.service.ExcelService;
import com.zg.autoform.service.ImportTemplateService;
import com.zg.common.core.A;
import com.zg.common.core.dao.autoform.DiyImportTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel处理服务实现
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ExcelServiceImpl implements ExcelService {

    private final ImportTemplateService templateService;

    // 文件大小阈值：5MB
    private static final long FILE_SIZE_THRESHOLD = 5 * 1024 * 1024;
    // 行数阈值：1000行
    private static final int ROW_COUNT_THRESHOLD = 1000;

    @Override
    public void generateTemplate(Long templateId, HttpServletResponse response) {
        try {
            // 1. 获取模板配置
            DiyImportTemplate template = templateService.getTemplateById(templateId);
            A.isInDatabase(template, "模板不存在");

            List<ImportFieldConfig> fields = templateService.getTemplateFieldConfigs(template.getId());
            A.isTrue(!fields.isEmpty(), "模板字段配置为空");

            // 2. 设置响应头
            String fileName = URLEncoder.encode(template.getName() + "_导入模板.xlsx", StandardCharsets.UTF_8.toString());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 3. 使用原生POI创建Excel
            try (Workbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("导入模板");

                // 创建样式
                CellStyle headerStyle = createHeaderStyle(workbook);
                CellStyle descStyle = createDescStyle(workbook);

                // 第一行：字段中文名
                Row labelRow = sheet.createRow(0);
                for (int i = 0; i < fields.size(); i++) {
                    Cell cell = labelRow.createCell(i);
                    cell.setCellValue(fields.get(i).getFieldLabel());
                    cell.setCellStyle(headerStyle);
                    // 设置列宽
                    Integer width = fields.get(i).getColumnWidth();
                    if (width != null && width > 0) {
                        sheet.setColumnWidth(i, width * 256);
                    } else {
                        sheet.setColumnWidth(i, 20 * 256);
                    }
                }

                // 第二行：字段名
                Row nameRow = sheet.createRow(1);
                for (int i = 0; i < fields.size(); i++) {
                    Cell cell = nameRow.createCell(i);
                    cell.setCellValue(fields.get(i).getFieldName());
                    cell.setCellStyle(headerStyle);
                }

                // 第三行：字段说明
                Row descRow = sheet.createRow(2);
                for (int i = 0; i < fields.size(); i++) {
                    ImportFieldConfig field = fields.get(i);
                    Cell cell = descRow.createCell(i);

                    StringBuilder desc = new StringBuilder();
                    desc.append(field.getFieldDescription() != null ? field.getFieldDescription() : "");
                    if (field.getRequired() != null && field.getRequired()) {
                        desc.append("【必填】");
                    }
                    if (field.getExampleData() != null) {
                        desc.append(" 示例：").append(field.getExampleData());
                    }

                    cell.setCellValue(desc.toString());
                    cell.setCellStyle(descStyle);
                }

                // 写入响应流
                workbook.write(response.getOutputStream());
                response.getOutputStream().flush();
            }

            log.info("生成Excel模板成功，模板ID: {}, 名称: {}", templateId, template.getName());

        } catch (Exception e) {
            log.error("生成Excel模板失败，模板ID: {}", templateId, e);
            throw new RuntimeException("生成Excel模板失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean needAsyncProcess(MultipartFile file) {
        if (file == null) {
            return false;
        }

        // 根据文件大小判断
        if (file.getSize() > FILE_SIZE_THRESHOLD) {
            return true;
        }

        // 根据预估行数判断
        int estimatedRows = estimateRowCount(file);
        return estimatedRows > ROW_COUNT_THRESHOLD;
    }

    @Override
    public int estimateRowCount(MultipartFile file) {
        if (file == null || file.getSize() == 0) {
            return 0;
        }

        // 简单估算：假设每行平均100字节
        long avgBytesPerRow = 100;
        return (int) (file.getSize() / avgBytesPerRow);
    }



    /**
     * 创建表头样式
     */
    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置对齐方式
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置字体
        Font font = workbook.createFont();
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        style.setFont(font);

        return style;
    }

    /**
     * 创建描述样式
     */
    private CellStyle createDescStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置对齐方式
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置字体
        Font font = workbook.createFont();
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 10);
        font.setItalic(true);
        style.setFont(font);

        return style;
    }
}
